package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.apache.http.client.HttpClient;
import org.aspectj.weaver.ast.Or;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Value("${sky.baidu.ak}")
    private String ak;
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 检查配送地址是否超出配送范围
     * @param address 收货地址
     */
    public void  checkOutRange(String address){
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        log.info(shopCoordinate);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        //返回的状态码如果不是0则解析失败
        if(!jsonObject.getString("status").equals("0") ){
            throw new OrderBusinessException("店铺地址解析失败");
        }
        //解析返回结果,result为json对象，因此需要getJSONObject来获取，同理location也是
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        //经度值
        String lng = location.getString("lng");
        //纬度值
        String lat = location.getString("lat");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        //获取收货地址经纬度
        map.put("address", address);
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        jsonObject = JSON.parseObject(userCoordinate);
        //返回的状态码如果不是0则解析失败
        if(!jsonObject.getString("status").equals("0")  ){
            throw new OrderBusinessException("店铺地址解析失败");
        }
        //解析返回结果,result为json对象，因此需要getJSONObject来获取，同理location也是
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        //经度值
        lng = location.getString("lng");
        //纬度值
         lat = location.getString("lat");
        //店铺经纬度坐标
        String userLngLat = lat + "," + lng;

        //路线规划
        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", 0);
        String driving = HttpClientUtil.doGet("https://api.map.baidu.com/direction/v2/driving", map);
        jsonObject = JSON.parseObject(driving);
        if(!jsonObject.getString("status").equals("0") ){
            throw new OrderBusinessException("配送路线规划失败");
        }
        JSONObject result = jsonObject.getJSONObject("result");
        if (result == null) {
            throw new OrderBusinessException("路线规划结果为空");
        }
        JSONArray routes = (JSONArray)result.get("routes");
        if (routes == null || routes.isEmpty()) {
            throw new OrderBusinessException("未找到配送路线");
        }
        Integer distance = (Integer)((JSONObject) routes.get(0)).get("distance");
        if (distance > 5000){
            throw new OrderBusinessException("超出配送范围");
        }

    }
    /**
     * 用户下单
     * @param dto
     * @return
     */
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //查询地址表获取收货人信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        String Detail = addressBook.getDetail();
        String provinceName = addressBook.getProvinceName();
        String cityName = addressBook.getCityName();
        String districtName = addressBook.getDistrictName();
        String address = provinceName + cityName + districtName + Detail;
        log.info("收货地址为：{}",address);
//        checkOutRange(address);
        if (addressBook == null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        //查询用户表，获取用户相关信息
        User user = userMapper.selectById(userId);
        if(user == null){
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }
        //查询购物车数据只查询自己名下的购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if(cartList == null && cartList.size() == 0){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //构造订单数据 ，存入orders表
        Orders orders = new Orders();
        //拷贝属性值
        BeanUtils.copyProperties(dto, orders);
        //补充缺失的属性
        orders.setNumber(System.currentTimeMillis()+""); // 订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);//代付款
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName()); //下单人
        ordersMapper.insert(orders);
        log.info("订单数据：{}", orders);
        //构造订单明细数据，存入order_detail表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        cartList.forEach(cart->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail,"id");
            //关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail); //添加到list中
        });
        //批量插入订单明细
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车,删除自己名下的购物车数据
        shoppingCartMapper.cleanShoppingCart(userId);
        //构造orderSubmit对象，返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.selectById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));

//        return vo;
        //模拟支付成功--修改订单状态
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        //通过websocket通知客户端
        Map map = new HashMap();
        map.put("type", 1); //1表示来单提醒 2表示用户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);
        //转成json字符串
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 查询历史订单数据
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrdersHistoryDto> page = ordersMapper.historyOrders(dto);
        page.getResult().forEach(e -> e.setOrderDetailList(orderDetailMapper.getByOrderId(e.getId())));
        log.info("查询历史订单数据：{}", page.getResult());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    @Transactional
    public void cancel(Long id)  throws  Exception{
        //取消订单实则就是改其状态码就可以了
        Orders orders = Orders.builder()
                        .id( id)
                        .status(Orders.CANCELLED)
                        .cancelReason("用户取消")
                        .cancelTime(LocalDateTime.now())
                        .build();
        Orders ordersMapperById = ordersMapper.getById(id);
        if(ordersMapperById == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (ordersMapperById.getStatus() > Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        if (ordersMapperById.getPayStatus().equals(Orders.TO_BE_CONFIRMED)){
            weChatPayUtil.refund(
                    ordersMapperById.getNumber(), //商户订单号
                    ordersMapperById.getNumber(), //商户退款单号
                    new BigDecimal(0.1),//退款金额，单位 元
                    new BigDecimal(0.1));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        ordersMapper.update(orders);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Orders getById(Long id) {
        Orders dto =  Orders.builder()
                                .id(id)
                                .build();
         Orders orders = ordersMapper.getById(id);
         BeanUtils.copyProperties(orders, dto);
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        dto.setOrderDetailList(list);
        log.info("查询订单详情：{}", dto);
        return dto;
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    @Transactional
    public void reOrder(Long id) {
        //查询当前订单
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        if (list == null || list.size() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //查到了订单详情(可能购买了多个商品，故有多条),添加到购物车
        log.info("再来一单的数据：{}", list);
        list.forEach(e -> {
            ShoppingCart cart = new ShoppingCart();
            if(e.getDishId() != null)  cart.setDishId(e.getDishId());
            if (e.getSetmealId() != null) cart.setSetmealId(e.getSetmealId());
            if (e.getDishFlavor() != null) cart.setDishFlavor(e.getDishFlavor());
            cart.setNumber(e.getNumber());
            cart.setAmount(e.getAmount());
            cart.setCreateTime(LocalDateTime.now());
            cart.setUserId(BaseContext.getCurrentId());
            cart.setImage(e.getImage());
            cart.setName(e.getName());
            cart.setAmount(e.getAmount());
            shoppingCartMapper.insert(cart);
        });
    }

    /**
     * 管理端订单搜索
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<Orders> page = ordersMapper.conditionSearch(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO vo = ordersMapper.statistics();
        return vo;
    }

    /**
     * 接单
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        Orders orders = Orders.builder()
                .id(dto.getId())
                .status(Orders.CONFIRMED) //设置为接单
                .build();
        log.info("接单：{}", orders);
        ordersMapper.update(orders);
    }

    /**
     * 拒单
     * @param dto
     */
    @Override
    @Transactional
    public void rejection(OrdersRejectionDTO dto) throws Exception {
        Orders ordersMapperById = ordersMapper.getById(dto.getId());
        if (ordersMapperById == null || ordersMapperById.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(ordersMapperById.getPayStatus().equals(Orders.PAID)){
            //已经支付需要退款
            weChatPayUtil.refund(
                    ordersMapperById.getNumber(), //商户订单号
                    ordersMapperById.getNumber(), //商户退款单号
                    new BigDecimal(0.1),//退款金额，单位 元
                    new BigDecimal(0.1));//原订单金额

            //支付状态修改为 退款
            ordersMapperById.setPayStatus(Orders.REFUND);
        }
        Orders orders = Orders.builder()
                .id(dto.getId())
                .status(Orders.CANCELLED) //设置为拒单
                .cancelReason(dto.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);

    }

    /**
     * 管理端取消订单
     * @param dto
     */
    @Override
    @Transactional
    public void adminCancelOrders(OrdersCancelDTO dto) throws Exception {
        Orders orders = ordersMapper.getById(dto.getId());
        if(orders == null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        //需要判断支付状态，已经支付需要退款
        if(orders.getPayStatus().equals(Orders.PAID)){
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.1),//退款金额，单位 元
                    new BigDecimal(0.1));//原订单金额
        }
        //补充缺失的信息
        Orders order = Orders.builder()
                .id(dto.getId())
                .status(Orders.CANCELLED) //设置为拒单
                .cancelReason(dto.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        ordersMapper.update(order);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    @Transactional
    public void deliveryOrders(Long id) {
        Orders ordersDB = ordersMapper.getById(id);
        if(ordersDB == null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        //判断订单状态，如果订单状态不是待派单则无法派送
        if (ordersDB.getStatus() != Orders.CONFIRMED) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.DELIVERY_IN_PROGRESS) //设置为派送中
                .build();
        ordersMapper.update(orders);

    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    @Transactional
    public void completeOrders(Long id) {
        Orders orderDB = ordersMapper.getById(id);
        if (orderDB == null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        if (orderDB.getStatus() != Orders.DELIVERY_IN_PROGRESS) throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        Orders orders = Orders.builder()
                .id(orderDB.getId())
                .status(Orders.COMPLETED) //设置为已完成
                .deliveryTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);

    }
}
